package com.app.business.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 发送短信工具类
 * 阿里巴巴
 */
//@Component
public class AliMessageUtil {

    @Value("${Oos.accessKeyId}")
    private String accessKeyId;
    @Value("${Oos.accessKeySecret}")
    private String secret;
    @Value("${message.templateCode}")
    private String templateCode;
    // 验证码长度
    private final Integer codeLength = 6;

    /**
     * 发送短信
     * （客户端根据对应格式产生短信验证码 -> 交给阿里服务端 -> 对应手机号）
     * @param phone 手机号
     * @return 此端产生的验证码
     */
    public String sendMessage(String phone) {
        // 随机产生一个验证码
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < codeLength; i++) {
            // 每次随机出一个数字（0-9）
            int r = random.nextInt(10);
            // 把每次随机出的数字拼在一起
            code.append(r);
        }
        // 发送短信
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, secret);

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        // request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "我的心理画");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return code.toString();
    }

}
